package com.dimples.dd.gateway.handler;

import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.dimples.dd.common.result.ResultCode;
import com.dimples.dd.gateway.util.WebFrameworkUtils;
import com.dimples.dd.common.result.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static com.dimples.dd.common.result.ResultCode.SYSTEM_EXECUTION_ERROR;

/**
 * Gateway 的全局异常处理器，将 Exception 翻译成 CommonResult + 对应的异常编号
 * <p>
 * 在功能上，和 dimples-framework-web-starter 的 BaseExceptionHandler 类是一致的
 *
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/6/11
 */
@Component
@Order(-1) // 保证优先级高于默认的 Spring Cloud Gateway 的 ErrorWebExceptionHandler 实现
@Slf4j
public class DDGatewayExceptionHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        // 已经 commit，则直接返回异常
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(ex);
        }

        // 转换成 CommonResult
        CommonResult<?> result;
        if (ex instanceof ResponseStatusException) {
            result = responseStatusExceptionHandler(exchange, (ResponseStatusException) ex);
        } else {
            result = defaultExceptionHandler(exchange, ex);
        }

        // 返回给前端
        return WebFrameworkUtils.writeJSON(exchange, result);
    }

    /**
     * 处理 Spring Cloud Gateway 默认抛出的 ResponseStatusException 异常
     */
    private CommonResult<?> responseStatusExceptionHandler(ServerWebExchange exchange, ResponseStatusException ex) {
        ServerHttpRequest request = exchange.getRequest();

        log.error(
                "请求发生异常，请求URI：{}，请求方法：{}，异常信息：{}",
                request.getPath(), request.getMethod(), ex.getMessage()
        );
        String errorMessage;
        if (ex instanceof NotFoundException) {
            String serverId = StrUtil.subAfter(ex.getMessage(), "Unable to find instance for ", true);
            serverId = StrUtil.replace(serverId, "\"", StrUtil.EMPTY);
            errorMessage = String.format("无法找到%s服务", serverId);
        } else if (StrUtil.containsIgnoreCase(ex.getMessage(), "connection refused")) {
            errorMessage = "目标服务拒绝连接";
        } else if (StringUtils.containsIgnoreCase(ex.getMessage(), HttpStatus.NOT_FOUND.toString())) {
            errorMessage = "未找到该资源";
        } else {
            errorMessage = "网关转发异常";
        }

        return CommonResult.error(ResultCode.GATEWAY_EXECUTION_ERROR.getCode(), errorMessage);
    }

    /**
     * 处理系统异常，兜底处理所有的一切
     */
    @ExceptionHandler(value = Exception.class)
    public CommonResult<?> defaultExceptionHandler(ServerWebExchange exchange, Throwable ex) {
        ServerHttpRequest request = exchange.getRequest();
        log.error("[defaultExceptionHandler][uri({}/{}) 发生异常]", request.getURI(), request.getMethod(), ex);
        // TODO dimples：是否要插入异常日志呢？
        // 返回 ERROR CommonResult
        return CommonResult.error(SYSTEM_EXECUTION_ERROR.getCode(), SYSTEM_EXECUTION_ERROR.getMsg());
    }
}
